package com.example.utils;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonMappingException;

public class JsonUtil {

    private static final ObjectMapper objectMapper = new ObjectMapper();

    // JSON字符串转Java对象
    public static <T> T fromJson(String json, Class<T> clazz) throws JsonMappingException, JsonProcessingException {
        return objectMapper.readValue(json, clazz);
    }

    // Java对象转JSON字符串
    public static String toJson(Object object) throws JsonProcessingException {
        return objectMapper.writeValueAsString(object);
    }

    // Java对象转JSON字符串并格式化
    public static String toJsonPretty(Object object) throws JsonProcessingException {
        return objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);
    }
}